package com.fy.oa.zc.crafts;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fy.oa.zc.domain.FySummaryView;
import com.fy.oa.zc.manager.AFyOA_FormEventManager;
import com.fy.oa.zc.manager.FyOA_FormEventManager;
import com.seeyon.ctp.util.UUIDLong;

public class FyOA_OperatingInstructionsManagerImpl extends AFyOA_FormEventManager implements FyOA_FormEventManager {
	// <value>草稿</value>
	// <value>编制</value>
	// <value>生效日期</value>
	// <value>版本号</value>
	// <value>审核</value>
	// <value>批准</value>
	private static final Log logger = LogFactory.getLog(FyOA_OperatingInstructionsManagerImpl.class);

	@Override
	public String dealFinishEvent(FySummaryView view) {
		logger.info("dealFinishEvent>>>>>>>>>>>>");
		Map<String, String> map = getValues(view.getSummaryid());
		String file_ref = map.get("草稿");
		String creator = map.get("编制");
		String effectiveDate = String.valueOf(map.get("生效日期")).substring(0, 10);
		String version = map.get("版本号");
		String check = map.get("审核");
		String approve = map.get("批准");
		System.out.println(file_ref);
		Long sub_ref = UUIDLong.longUUID();
		List<Object[]> list = new ArrayList<Object[]>();
		List<Map<String, Object>> fileList = jdbcTemplate.queryForList(
				("select a.FILE_URL ID, a.FILENAME FILENAME from CTP_ATTACHMENT a where a.SUB_REFERENCE =?"), file_ref);
		
		for (int i = 0; i < fileList.size(); i++) {
			InputStream is = fyOARestClient.download(String.valueOf(fileList.get(i).get("ID")));
			try {
				String fileName = (String) fileList.get(i).get("FILENAME");
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				Workbook wb = null;
				if (fileName.endsWith("x"))
					wb = new XSSFWorkbook(is);
				else if (fileName.endsWith("s"))
					wb = new HSSFWorkbook(is);
				
				Sheet sheet = wb.getSheetAt(0);
				Row row = sheet.getRow(0);
				Cell cell = null;
				int index = 0;
				for (; (cell = row.getCell(index)) != null; index++) {
					String value = cell.getStringCellValue();
					if (value != null && "批准".equals(value.replaceAll(" ", ""))) {
						break;
					}
				}
				index++;
				setCell(sheet.getRow(0).getCell(index), approve);
				setCell(sheet.getRow(1).getCell(index), check);
				setCell(sheet.getRow(2).getCell(index), creator);
				setCell(sheet.getRow(3).getCell(index), effectiveDate);
				setCell(sheet.getRow(4).getCell(index), version);
				wb.write(baos);
				baos.flush();
				byte[] fileBytes = baos.toByteArray();
				baos.close();
				is.close();
				list.add(new Object[] { UUIDLong.longUUID(), view.getSummaryid(), sub_ref,
						Long.valueOf(fyOARestClient.upload(fileBytes, fileName)) });
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		ObjectMapper mapper = new ObjectMapper();
		try {
			System.out.println(mapper.writeValueAsString(list));
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		jdbcTemplate.batchUpdate("update CTP_FILE f set f.CATEGORY = 2 where ? is not null and ? is not null and ? is not null and f.id = ?", list);
		
		jdbcTemplate.batchUpdate(
				"insert into CTP_ATTACHMENT (id,REFERENCE,sub_REFERENCE,category,\"TYPE\",filename,file_url,MIME_TYPE,createdate,attachment_size) select ?,?,?,f.CATEGORY,f.\"TYPE\",f.FILENAME,f.id,f.MIME_TYPE,f.CREATE_DATE,f.FILE_SIZE from CTP_FILE f where f.ID=?",
				list);

		jdbcTemplate.update(
				"update formmain_4402 f set f.field0007 = ? where f.id = (select s.FORM_RECORDID from COL_SUMMARY s where s.id = ?)",
				sub_ref, view.getSummaryid());
		System.out.println(list);
		
		logger.info("dealFinishEvent<<<<<<<<<<<<<<<<<<<<<<<<<<<");

		return view.toString();
	}

	private void setCell(Cell cell, String value) {
		cell.setCellType(Cell.CELL_TYPE_STRING);
		cell.setCellValue(value);
	}
}
